:: Set encodeing to UTF-8 for console
@CHCP 65001
:: esp32平台交叉编译 thmar 脚本
:: 基于conan 安装依赖库,并编译安装到本地目录
:: 2024/08/28

ECHO OFF 
SETLOCAL
where cmake
if errorlevel 1 (
	ECHO cmake NOT FOUND.
	exit /B -1
)
ECHO cmake found
where conan
if errorlevel 1 (
	ECHO conan NOT FOUND.
	exit /B -1
)
ECHO conan found
:: 检查conan 版本,要求conan 2
conan --version | findstr /C:"Conan version 2"
if errorlevel 1 (
	ECHO coan 2 required.
	exit /B -1
)
where python
if errorlevel 1 (
	ECHO python NOT FOUND.
	exit /B -1
)
ECHO python found
:: 检查Python 版本,要求Python 3
python --version | findstr /C:"Python 3"
if errorlevel 1 (
	ECHO python 3 required.
	exit /B -1
)
SET machine=xtensa-esp32-elf
SET build_type=Release
SET prj_folder=%sh_folder%\build\%machine%
SET install_prefix=%sh_folder%\release\thmar-%machine%

:: parse command arguments
:loop
IF x%1 == x GOTO :pare_end
IF /I "%1" == "/RELEASE" SET build_type=Release
IF /I "%1" == "/DEBUG" SET build_type=Debug
IF /I "%1" == "/MACHINE" SET machine=%2
IF /I "%1" == "/PRJ_FOLDER" SET prj_folder=%2
IF /I "%1" == "/INSTALL_PREFIX" SET install_prefix=%2
SHIFT
GOTO :loop
:pare_end

:: 获取脚本所在目录
SET sh_folder=%~dp0
:: 删除最后的 '\'
SET sh_folder=%sh_folder:~0,-1%

:: 生成项目工程文件
IF EXIST %prj_folder% RMDIR %prj_folder% /s/q 
MKDIR %prj_folder% || EXIT /B
PUSHD %prj_folder% || EXIT /B
:: conan 安装依赖库到%prj_folder%目录下
conan install "%sh_folder%" -pr:h %sh_folder%\conan2\profiles\esp32_gcc -pr:b default ^
	-of %prj_folder% ^
	-s build_type=%build_type% ^
	-o with_paho=False -o build_test=False ^
	--build missing || EXIT /B
:: -pr:h esp32_gcc 指定目标平台的profile
:: -pr:b default  指定编译平台的profile
:: --build missing 编译缺少的依赖库
echo "creating Project for %machine% ..."
cmake "%sh_folder%" -G "MinGW Makefiles" -DCMAKE_BUILD_TYPE=%build_type% ^
	-DCMAKE_TOOLCHAIN_FILE=%prj_folder%\conan_toolchain.cmake ^
	-DCMAKE_INSTALL_PREFIX=%install_prefix% ^
	-DCMAKE_SH="CMAKE_SH-NOTFOUND" -DCMAKE_POLICY_DEFAULT_CMP0091="NEW" || EXIT /B

echo "building Project for %machine% ..."
cmake --build . --config %build_type% --target install -- -j 8 || EXIT /B 

POPD || EXIT /B

ENDLOCAL